import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import renderModal, {
    getModelValue,
    initModelValue,
    renderForm,
    type FormModalDto
} from '@/components/modal/Modal'
import { updatePayManagerUser } from '@/api/pay'
import type { FilterDto } from '@/render/FilterRender'
import type { CompanyInfoDto, PeriodInfoDto, PeriodInfoReqDto } from '@/api/company/types'
import { getReceiptData, goBack } from '@/utils/util'
import { getPeriodInsuranceCompanyList, getPeriodPlanList } from '@/api/insurance/company'
import type { OptionDto } from '@/components/low-code/types'
import { Button, message } from 'ant-design-vue'
import CustomTitle from '@/components/custom-title/Index'
import SuccessComponent from './SuccessComponent'
import { getPriodInfo } from '@/api/company'
import { ProductTypeEnum } from '@/const/enum'
import dayjs from 'dayjs'
import type { SaleReqDto } from '@/api/deal/types'
import { openPeriodInsurance } from '@/api/product'
import type { OpenPeriodReqDto } from '@/api/product/types'
import { addContact, editContact } from '@/api/deal'

@Component({
    expose: ['getData']
})
export class OpenPeriod extends Render {
    @Prop() companyBasicInfo!: CompanyInfoDto

    isSuccess = false

    basicData = {} as PeriodInfoDto

    get periodCompanyTypeListValue() {
        const data = getModelValue(this.planFormConfig)
        return data.periodCompanyTypeList
    }

    @Emit('refresh')
    handleRefresh() {}

    @Watch('periodCompanyTypeListValue')
    async handleWatchPeriodCompanyTypeList(val: string[]) {
        let options = [] as OptionDto[]
        if (val?.length) {
            const res = (
                await getPeriodPlanList({
                    insureCompanys: val.join(',')
                })
            ).map((item) => ({
                label: item.dictLabel,
                value: item.remark,
                disabled: false
            }))
            res.forEach((i) => {
                i.disabled = this.basicData.periodPlanTypeList?.includes(i.value as string)
            })
            options = res
        }
        this.planFormConfig.items.periodPlanTypeList.options = options
    }

    basicFormConfig = this.initFormConfig() as FormModalDto
    initFormConfig() {
        return {
            title: '',
            width: '400px',
            theme: 'light',
            show: false,
            items: {
                saleId: {
                    name: '所属销售',
                    element: 'select',
                    optionsType: 'saleList',
                    required: true
                },
                channelId: {
                    name: '收款渠道',
                    element: 'select',
                    optionsType: 'channel',
                    required: true,
                    callback: {
                        change: async (value: number) => {
                            this.basicFormConfig.items.receiptId.value = ''
                            if (value) {
                                this.basicFormConfig.items.receiptId.options =
                                    await getReceiptData(value)
                            } else {
                                this.basicFormConfig.items.receiptId.options = []
                            }
                        }
                    }
                },
                receiptId: {
                    name: '收款账号',
                    element: 'select',
                    required: true
                },
                openQrProjectEnsure: {
                    name: '开通快捷投保',
                    element: 'switch',
                    params: {
                        activeValue: 1,
                        inactiveValue: 2,
                        activeText: '开启',
                        inactiveText: '关闭'
                    }
                },
                creditCodePicture: {
                    name: '营业执照',
                    element: 'upload',
                    params: {
                        autoUpload: false,
                        accept: '.png,.jpg,.jpeg',
                        listType: 'text'
                    }
                }
            },
            complete: async () => {
                const data = getModelValue(this.basicFormConfig)
                await updatePayManagerUser(data)
                message.success('更新成功')
                this.basicFormConfig.show = false
            },
            cancel: () => {
                this.basicFormConfig.show = false
            },
            init: () => {}
        } as FormModalDto
    }
    basicForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    planFormConfig = this.initPlanFormConfig() as FormModalDto
    initPlanFormConfig() {
        return {
            title: '',
            width: '400px',
            theme: 'light',
            show: false,
            items: {
                periodCompanyTypeList: {
                    name: '保险公司',
                    element: 'select',
                    optionsType: 'insurCompany',
                    defaultValue: [],
                    params: {
                        clearable: false
                    },
                    multiple: true,
                    required: true
                },
                periodPlanTypeList: {
                    name: '投保方案',
                    element: 'select',
                    defaultValue: [],
                    params: {
                        clearable: false
                    },
                    multiple: true,
                    required: true
                }
            },
            complete: async () => {
                const data = getModelValue(this.basicFormConfig)
                await updatePayManagerUser(data)
                message.success('更新成功')
                this.basicFormConfig.show = false
            },
            cancel: () => {
                this.basicFormConfig.show = false
            },
            init: () => {}
        } as FormModalDto
    }
    planForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    filterBtnConfig() {
        return {} as FilterDto
    }

    async initData() {
        const res = await getPriodInfo(this.companyBasicInfo.companyId)
        this.basicData = res

        if (this.basicData.channelId) {
            this.basicFormConfig.items.receiptId.options = await getReceiptData(
                this.basicData.channelId
            )
        }
        if (this.basicData?.periodCompanyTypeList) {
            const res = await getPeriodInsuranceCompanyList()
            res.forEach((i) => {
                i.disabled = this.basicData.periodCompanyTypeList.includes(i.dictValue)
            })
            this.planFormConfig.items.periodCompanyTypeList.options = res?.map((item) => ({
                label: item.dictLabel,
                value: item.dictValue,
                disabled: item.disabled || false
            }))
        }

        initModelValue(this.basicFormConfig, this.basicData)

        if (this.basicData.isOpenPeriod) {
            initModelValue(this.planFormConfig, this.basicData)
        }
    }

    async onSubmit() {
        await this.basicForm.validate()
        await this.planForm.validate()
        const basicFormData = getModelValue(this.basicFormConfig)
        const planFormData = getModelValue(this.planFormConfig)

        const { saleId, creditCodePicture, ...otherData } = basicFormData

        const params = {
            id: this.companyBasicInfo.companyId,
            isOpenPeriod: 1,
            ...otherData,
            ...planFormData
        } as OpenPeriodReqDto

        params.creditCodePicture =
            creditCodePicture?.[0]?.url ?? creditCodePicture?.[0]?.base64 ?? ''

        const saleParams = {
            companyId: this.basicData.companyId,
            id: this.basicData.dealId,
            productType: ProductTypeEnum.PERIOD,
            saleId: saleId,
            serviceStartTime: dayjs().startOf('day').format('YYYY-MM-DD'),
            serviceState: 0
        } as SaleReqDto
        await openPeriodInsurance(params)

        if (!this.basicData.saleId) {
            await addContact(saleParams)
        } else {
            await editContact({
                ...saleParams,
                saleOldId: this.basicData.saleId
            })
        }
        message.success('更新成功')
        this.isSuccess = true
    }

    async created() {
        await this.initData()
        this.basicForm = renderForm(this.basicFormConfig)
        this.planForm = renderForm(this.planFormConfig)
    }

    renderStatistics() {
        return <></>
    }

    renderRightBtns() {
        return <></>
    }

    render() {
        return (
            this.isSuccess ? (
                <div class="h-full flex justify-center items-center">
                    <SuccessComponent hint="已成功开通了长期保产品，需要继续添加方案，可在保险客户中心添加" />
                </div>
            ) : 
                <div class="flex flex-col h-full">
                    <div class="flex-1 overflow-auto">
                        <CustomTitle>开通长期保</CustomTitle>
                        <div class="pt-20px">{this.basicForm.element()}</div>
                        <CustomTitle>添加方案</CustomTitle>
                        <div class="pt-20px">{this.planForm.element()}</div>
                    </div>
                    <div class="pt-19px flex justify-center gap-20px">
                        <Button onClick={goBack}>取消</Button>
                        <Button type="primary" onClick={this.onSubmit}>
                            确认
                        </Button>
                    </div>
                </div>
        )
    }
}

export default toNative<{ companyBasicInfo?: CompanyInfoDto }, { refresh: () => void }>(OpenPeriod)
